package com.phb.puhuibao.web.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.idap.clinic.entity.UploadFile;
import com.idap.web.common.controller.Commons;
import com.idp.pub.service.IBaseService;
import com.idp.pub.utils.DESUtils;
import com.idp.pub.utils.RSAUtils;
import com.idp.pub.web.controller.BaseController;
import com.opensymphony.oscache.util.StringUtil;
import com.phb.puhuibao.common.Functions;
import com.phb.puhuibao.common.InitListener;
import com.phb.puhuibao.entity.Company;
import com.phb.puhuibao.entity.ExperienceValue;
import com.phb.puhuibao.entity.Invite;
import com.phb.puhuibao.entity.MobileUser;
import com.phb.puhuibao.entity.MobileUserExtra;
import com.phb.puhuibao.entity.MobileUserHexagram;
import com.phb.puhuibao.entity.MuserFollow;
import com.phb.puhuibao.entity.UserCard;
import com.phb.puhuibao.entity.UserSession;
import com.phb.puhuibao.service.MobileUserService;
import com.phb.puhuibao.service.impl.MuserFollowServiceImpl;

@Controller
@RequestMapping(value = "/userInformation")
public class MobileUserController extends BaseController<MobileUser, String> {
	final Log log = LogFactory.getLog(MobileUserController.class);
	@Resource(name = "mobileUserService")
	public void setBaseService(IBaseService<MobileUser, String> baseService) {
		super.setBaseService(baseService);
	}
	@Resource(name = "uploadFileService")
	private IBaseService<UploadFile, String> uploadFileService;
	@Resource(name = "mobileUserExtraService")
	private IBaseService<MobileUserExtra, String> mobileUserExtraService;
	@Resource(name = "userSessionService")
	private IBaseService<UserSession, String> userSessionService;
	@Resource(name = "companyService")
	private IBaseService<Company, String> companyService;
	@Resource(name = "inviteService")
	private IBaseService<Invite, String> inviteService;
	@Resource(name = "mobileUserService")
	private MobileUserService mobileUserService;
	@Resource(name = "muserFollowService")
	private MuserFollowServiceImpl muserFollowService;
	@Resource(name = "commons")
	private Commons commons;

	//-----用户注册-----
		@RequestMapping(value="saveMobileUserForUser")
		@ResponseBody
		public Map<String, Object> saveMobileUserForIOS(@RequestParam String userTel, @RequestParam String userPwd) {
			Map<String, Object> data = new HashMap<String, Object>();
			
			try {
				if (!Functions.isMobile(userTel)) {
					data.put("message", "请输入正确的手机号！");
					data.put("status", 0);
					return data;
				}

				Map<String,Object> params=new HashMap<String,Object>();
				params.put("userTel", userTel);
				MobileUser u = this.getBaseService().unique(params);
				if (u != null) {
					data.put("message", "该手机号已注册，请登录！");
					data.put("status", 0);
					return data;
				}
				MobileUser entity = new MobileUser();
				entity.setUserTel(userTel);
				entity.setUserPwd(DESUtils.decrypt(userPwd)); 							
			    mobileUserService.userCreate(entity);
			    UserSession us=new UserSession();
			    us.setUserId(entity.getUserId());
			    us.setSessionId(this.getSessionId());
			    userSessionService.save(us);
				data.put("result", entity);
				data.put("message", "注册成功！");
				data.put("status", 1);
				return data;
			} catch (Exception e) {
				e.printStackTrace();
				log.error("注册失败:"+e);
				
				data.put("message", "注册保存失败！" );
				data.put("status", 0);			
				return data;
			}
			
		}
	
	
	
    //-----用户登录-----
	@RequestMapping(value="mobileLoginForUser")
	@ResponseBody
	public Map<String, Object> mobileLoginForUser(@RequestParam String userTel, @RequestParam String userPwd) {
		Map<String, Object> data = new HashMap<String, Object>();
		
		if (!Functions.isMobile(userTel)) {
			data.put("message", "请输入正确的手机号！");
			data.put("status", 0);
			return data;
		}
		try {
		Map<String,Object> params=new HashMap<String,Object>();
		params.put("userTel", userTel);
		MobileUser entity = this.getBaseService().unique(params);
		
		if (entity == null) {
			data.put("message", "该手机号没注册！");
			data.put("status", 0);
		} else if (DESUtils.decrypt(userPwd).length()<=0||!DESUtils.decrypt(userPwd).equals(entity.getUserPwd())) {
		
			data.put("message", "密码错误！");
			data.put("status", 0);			
		} else {
			if(StringUtil.isEmpty(entity.getUserName()) ){
				entity.setUserName(entity.getUserTel().substring(0, 3)+"****"+entity.getUserTel().substring(7, 11));
			}

			UserSession us = new UserSession();
			int sessionId=this.getSessionId();
			us.setSessionId(sessionId);
			us.setUserId(entity.getUserId());
			userSessionService.update(us);			
			InitListener.sessionhash.put(entity.getUserId(),sessionId);// 把这个用户的随机数 更新到内存
			
			
				params=new HashMap<String,Object>();
				params.put("userId", entity.getUserId());
				Company company=companyService.unique(params);
				if(company==null){
					data.put("userOrCompany", "个人");
				}else{
					data.put("userOrCompany", "企业");
				}
				data.put("result", entity);
				data.put("token", sessionId);
				data.put("message", "登录成功！");
				data.put("status", 1);
			
			
		}
		} catch (Exception e) {
			// TODO: handle exception
			data.put("message", "登录失败！");
			data.put("status", 0);
		} 
		return data;
	}
	//-----上传图片-----
	@RequestMapping(params = "method=uploadPicture", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadPicture(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		MultipartFile multipartFile = null;
		for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
			multipartFile = set.getValue();// 文件名
		}
		String orgname = multipartFile.getOriginalFilename();// 获取原始文件名
		String fileType = orgname.substring(orgname.lastIndexOf(".") + 1, orgname.length());
		String fileName = System.currentTimeMillis() + "." + fileType;
		String filePath = commons.getFileUploadPath() + "/" + fileName;
		String mkpath = commons.getFileUploadPath();
		File file = new File(filePath);
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			File mkdir = new File(mkpath);
			if (!mkdir.exists()) {
				mkdir.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			multipartFile.transferTo(file);
			
			UploadFile uploadFile = new UploadFile();
			uploadFile.setFileName(fileName);
			uploadFile.setFileType(fileType);
			uploadFile.setFilePath(filePath);
			uploadFile.setOrgFileName(orgname);
			uploadFile = uploadFileService.save(uploadFile);
			data.put("result", uploadFile.getId());
			data.put("message", "上传成功！");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("message", "图片上传失败！");
			data.put("status", 0);
		}
		return data;
	}
	//-----查看用户个人信息-----
	@RequestMapping(value="getUserById")
	@ResponseBody
	public Map<String, Object> getUserById(@RequestParam String userId){
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("userId", userId);						
		try {
			MobileUser entity = this.getBaseService().unique(params);
			entity.setUserPwd(null);
			entity.setPayPassword(null);
			entity.setAddress(null);
			entity.setIdNumber(null);
			entity.setUserIdcardPicture(null);
			entity.setIdcardFront(null);
			entity.setIdcardBack(null);
			entity.setCreateTime(null);
		    data.put("result", entity);
			data.put("message", "个人信息获取成功！");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("message", "个人信息获取失败！");
			data.put("status", 0);			
		}
	return data;
	}
	//-----编辑个人信息-----
	@RequestMapping(value="modifyUserInformation")
	@ResponseBody
	public Map<String, Object> modifyUserInformation(@RequestParam String userId,      @RequestParam String userName,   
			                                         @RequestParam String sex,         @RequestParam String age,
												     @RequestParam String height,      @RequestParam String weight,
												     @RequestParam String userEmail,   @RequestParam String userQq, 
												     @RequestParam String userWechat,  @RequestParam String jobIntension,
												     @RequestParam String school,      @RequestParam String eduBackground,
												     @RequestParam String profession,  @RequestParam String evaluation,
												     @RequestParam String experience,  @RequestParam String address,
                                                     @RequestParam String id){
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("userId", userId);	
	
		try {
	    MobileUser entity = new MobileUser();
		int int_sex = 0;//0:不限   1：女    2：男
		if ("1".equals(sex)) {
			int_sex = 1;
		}else if ("2".equals(sex)){
			int_sex = 2;
		}
		int int_age = 0;
		if (age.length() > 0 && StringUtils.isNumeric(age)) {
			int_age = Integer.parseInt(age);
			if (int_age > 127) {
				data.put("message", "用户年龄不合理！");
				data.put("status", 0);			
				return data;
			}
		}
		if (userId.length() > 0 && StringUtils.isNumeric(userId)) {
			
		} else {
			data.put("message", "用户id非法！");
			data.put("status", 0);			
			return data;
		}	
		MobileUser u = this.getBaseService().unique(params);
		if (u.getPhoto() != null && u.getPhoto().length() > 0) {
				params = new HashMap<String,Object>();
				params.put("id", "'" + u.getPhoto() + "'");
				uploadFileService.delete(params);
			}
		entity.setPhoto(id);
		
		String province="";
		String city="";
		String area="";
		if (address!=null&&!"".equals(address)){
			String [] adr=address.split(",");
			province=adr[0];
			city=adr[1];
			area=adr[2];
		}
		entity.setUserId(Integer.parseInt(userId));
		entity.setUserName(userName);
		entity.setSex(int_sex);
		entity.setAge(int_age);
		if(height!=null&&!"".equals(height)){
			entity.setHeight(Float.parseFloat(height));
		}
		if(weight!=null&&!"".equals(weight)){
			entity.setWeight(Float.parseFloat(weight));
		}
		
		entity.setUserEmail(userEmail);
		entity.setUserQq(userQq);
		entity.setUserWechat(userWechat);
		entity.setJobIntension(jobIntension);
		entity.setUserProvince(province);
		entity.setUserCity(city);
		entity.setUserArea(area);
		entity.setSchool(school);
		entity.setEduBackground(eduBackground);
		entity.setProfession(profession);
		entity.setEvaluation(evaluation);
		entity.setExperience(experience);		
	
	    this.getBaseService().update(entity);
		    data.put("result", entity);
			data.put("message", "保存成功！");
			data.put("status", 1);
		} catch (Exception e) {
			data.put("message", "网络异常！");
			data.put("status", 0);			
		}
	return data;
	}
	
	//-----核验手机号是否正确或者是否注册过-----
	@RequestMapping(value="checkMobile")
	@ResponseBody
	public Map<String, Object> checkMobile(@RequestParam String userTel) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (!Functions.isMobile(userTel)) {
			data.put("message", "请输入正确的手机号！");
			data.put("status", 0);
			return data;
		}

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("userTel", userTel);
		MobileUser entity = this.getBaseService().unique(params);
		if (entity != null) {
			data.put("result", true);
			data.put("message", "该手机号已注册，请登录！");
		} else {
			data.put("result", false);
			data.put("message", "请继续注册");
		}
		data.put("status", 1);			
		return data;
	}
	//-----产生sessionId-----
	public int getSessionId(){
		int sessionId = (int) (Math.random()*(999999999-100000000)+100000000);  
		return sessionId;
	}
	//-----个人认证-----
	@RequestMapping(value="userCertify")
	@ResponseBody
	public Map<String ,Object> userCertify(@RequestParam String userId , @RequestParam String userName,
			                               @RequestParam String idNumber , @RequestParam String  userIdcardPicture,
			                               @RequestParam String idcardFront , @RequestParam String idcardBack){
		Map<String , Object> data=new HashMap<String , Object>();	
		Map<String , Object> params=new HashMap<>();
		params.put("userId", userId);
		MobileUser entity = this.getBaseService().unique(params);
		if(entity==null){
			data.put("message", "用户不存在，请先注册！");
			data.put("status", 0);
			return data;
		}
        entity.setUserName(userName);		
		entity.setIdNumber(idNumber);
        entity.setUserIdcardPicture(userIdcardPicture);
		entity.setIdcardFront(idcardFront);
		entity.setIdcardBack(idcardBack);
		if(entity.getCertifyStatus()==0){
			entity.setCertifyStatus(1);
		}else if(entity.getCertifyStatus()==2){
            entity.setCertifyStatus(3);
		}
		try {
			this.getBaseService().update(entity);
			data.put("message", "个人认证成功！");
			data.put("status", 1);
		} catch (Exception e) {
			// TODO: handle exception
			data.put("message", "个人认证失败！");
			data.put("status", 0);
		}
		return data;
	}
	//-----企业认证-----
	@RequestMapping(value="enterpriseCertify")
	@ResponseBody	
public Map<String ,Object> enterpriseCertify(@RequestParam String userId , @RequestParam String registrationNum,
		                                     @RequestParam String companyName, @RequestParam String id ,
		                                     @RequestParam String companyId ){
	Map<String , Object> data=new HashMap<String , Object>();	
	Map<String , Object> params=new HashMap<String , Object>();	
	params.put("userId", userId);
	try {
	MobileUser entity = this.getBaseService().unique(params);
	if(entity==null){
		data.put("message", "用户不存在，请先注册！");
		data.put("status", 0);
		return data;
	}
	params=new HashMap<String , Object>();	
	params.put("companyId", companyId);
	
	Company company=companyService.unique(params);
	company.setUserId(userId);
	company.setRegistrationNum(registrationNum);
	company.setCompanyName(companyName);
	company.setBusinessLicense(id);
	if(entity.getCertifyStatus()==0){
		entity.setCertifyStatus(2);
	}else if(entity.getCertifyStatus()==1){
        entity.setCertifyStatus(3);
	}
	

		companyService.update(company);
		data.put("message", "企业认证成功！");
		data.put("status", 1);
	} catch (Exception e) {
		// TODO: handle exception
		data.put("message", "企业认证失败！");
		data.put("status", 0);
	}
	return data;	
	}
   //-----用户修改登录密码-----
@RequestMapping(value="modifyPassword")
@ResponseBody
public Map<String, Object> modifyPassword(@RequestParam String userTel, @RequestParam String oldUserPwd, @RequestParam String userPwd) {
	Map<String,Object> params=new HashMap<String,Object>();
	params.put("userTel", userTel);
	params.put("userPwd", oldUserPwd);
	MobileUser u = this.getBaseService().unique(params);
	if (u == null) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("message", "该手机号及密码不匹配！");
		data.put("status", 0);
		return data;
	}
	MobileUser entity = new MobileUser();
	entity.setUserId(u.getUserId());
	entity.setUserPwd(DESUtils.decrypt(userPwd));
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		this.getBaseService().update(entity);
		data.put("message", "密码修改成功！");
		data.put("status", 1);
	} catch (Exception e) {
		data.put("message", "密码修改失败！" + e.getMessage());
		data.put("status", 0);				
	}
	
	return data;
}
//-----忘记密码-----
@RequestMapping(value="findPassword")
@ResponseBody
public Map<String, Object> findPasswordForAndroid(@RequestParam String userTel, @RequestParam String password) {
	Map<String, Object> data = new HashMap<String, Object>();
	Map<String,Object> params = new HashMap<String,Object>();
	params.put("userTel", userTel);
	MobileUser u = this.getBaseService().unique(params);
	if (u == null) {
		data.put("message", "该手机号未注册！");
		data.put("status", 0);
		return data;
	}
	MobileUser entity = new MobileUser();
	entity.setUserId(u.getUserId());
	entity.setUserPwd(DESUtils.decrypt(password));
	try {
		this.getBaseService().update(entity);
	} catch (Exception e) {
		data.put("message", "登录密码找回失败！" + e.getMessage());
		data.put("status", 0);			
		return data;
	}
	data.put("message", "登录密码找回成功！");
	data.put("status", 1);
	return data;
}

	//-----绑定邮箱-----
	@RequestMapping(value="bindEmail")
	@ResponseBody
	public Map<String, Object> bindEmail(@RequestParam int userId, @RequestParam String userEmail) {
		Map<String, Object> data = new HashMap<String, Object>();
        try {
    		Map<String, Object> params = new HashMap<String, Object>();
    		params.put("userId", userId);
    		MobileUser user = this.getBaseService().unique(params);
    		user.setUserEmail(userEmail);
    		this.getBaseService().update(user);
    		data.put("message", "邮箱绑定成功！");
    		data.put("status", 1);
        } catch (Exception e) {
        	data.put("message", "邮箱绑定失败！");
    		data.put("status", 0);			
        }
		return data;
	}
	//-----编辑简历-----
	@RequestMapping(value="modifyResume")
	@ResponseBody
	public Map<String, Object> modifyResume(@RequestParam int userId) {
		Map<String, Object> data = new HashMap<String, Object>();
        
		return data;
	}

}
